package cn.com.agree.dopomapping.valueobjectmapping.singletonpomapping.infrastructure.repositoryimpl;

import cn.com.agree.dopomapping.valueobjectmapping.singletonpomapping.domain.CustomerDO;
import cn.com.agree.dopomapping.valueobjectmapping.singletonpomapping.domain.repository.CustomerRepository;
import cn.com.agree.dopomapping.valueobjectmapping.singletonpomapping.infrastructure.converter.AddressValueObjConverter;
import cn.com.agree.dopomapping.valueobjectmapping.singletonpomapping.infrastructure.converter.CustomerConverter;
import cn.com.agree.dopomapping.valueobjectmapping.singletonpomapping.infrastructure.mapper.AddressValueObjPOMapper;
import cn.com.agree.dopomapping.valueobjectmapping.singletonpomapping.infrastructure.mapper.CustomerPOMapper;
import cn.com.agree.dopomapping.valueobjectmapping.singletonpomapping.infrastructure.po.AddressValueObjPO;
import cn.com.agree.dopomapping.valueobjectmapping.singletonpomapping.infrastructure.po.CustomerPO;
import cn.hutool.core.collection.CollUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

@Repository
public class CustomerRepositoryImpl implements CustomerRepository {

    @Autowired
    private CustomerPOMapper customerPOMapper;
    @Autowired
    private AddressValueObjPOMapper addressPOMapper;
    @Autowired
    private CustomerConverter customerConverter;
    @Autowired
    private AddressValueObjConverter addressConverter;

    @Override
    public CustomerDO findById(String id) {
        CustomerPO customerPO = customerPOMapper.selectById(id);
        if (Objects.isNull(customerPO)) {
            return null;
        }
        AddressValueObjPO addressValueObjPO = addressPOMapper.findByCustomerId(customerPO.getId());
        return customerConverter.toEntity(customerPO, addressValueObjPO);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public CustomerDO save(CustomerDO customerDO) {
        CustomerPO customerPO = customerConverter.toPO(customerDO);
        customerPOMapper.insert(customerPO);

        AddressValueObjPO addressValueObjPO = addressConverter.toPO(customerDO.getAddress(), customerPO.getId());
        addressPOMapper.insert(addressValueObjPO);
        return customerConverter.toEntity(customerPO, addressValueObjPO);
    }

}
